package openjdk.server;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by boot on 1/11/16.
 * 对于每一个请求，单独开一个线程来进行相应的逻辑处理，如果客户端的数据传递并不是一直进行的，
 * 而是断断续续的，则相应的线程需要I/O等待，并进行上下文切换。
 */
public class BIOServer {
    public void cli() {
        String hello = "Hello world";
        Socket client = null;
        try {
            client = new Socket("127.0.0.1", 9999);
            OutputStream os = client.getOutputStream();
            os.write(hello.getBytes());
            os.flush();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        try {
            while (true) {
                Socket socket = serverSocket.accept();
                new Thread(new ProcessJob(socket)).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class ProcessJob implements Runnable {
        private Socket s;

        public ProcessJob(Socket socket) {
            this.s = socket;
        }

        @Override
        public void run() {
            int cnt = 0;
            byte[] b = new byte[1024];
            try {
                while ((cnt = s.getInputStream().read(b)) > 0) {
                    System.out.write(b, 0, cnt);
                }
                s.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
